<template>
  <FIModel v-model="visible" title="分配用户组" @close="closeClick" :showFotter="false">
    <el-row :gutter="20">
      <el-col :span="8">
        <FIFormItem prop="loginName" label="登录账号">
          <span>{{ editData.loginName }}</span>
        </FIFormItem>
      </el-col>
      <el-col :span="8">
        <FIFormItem prop="userName" label="用户姓名">
          <span>{{ editData.userName }}</span>
        </FIFormItem>
      </el-col>
      <el-col :span="8">
        <FIFormItem prop="deptCname" label="用户所属部门">
          <span>{{ editData.deptCname }}</span>
        </FIFormItem>
      </el-col>
    </el-row>

    <FITable
      ref="tableRef"
      class="box-radius2"
      title="记录集"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="dataList"
      primaryKey="groupId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      insertable
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      :showSaveModel="false"
      :settingConfig="settingConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
    >
      <template #headerBtn>
        <FIButton id="saveGroupUsers" border style="margin-right: 10px" @click.stop="saveClick"></FIButton>
        <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          buttonText="删除"
          beforePopText="请选择一条数据"
          :btn-binds="{ id: 'deleteGroupUsers', border: true }"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn>
      </template>
      <template #groupEname="{ scope }">
        <!-- <FIAutoInput
          v-if="scope.row._isNew"
          v-model="scope.row.groupEname"
          :options="userGroupList"
          value-key="groupEname"
          :displayKey="['groupEname', 'groupCname']"
          @select="handleSelect($event, scope.$index)"
          usePagination
          @load-more="loadMore"
        >
          <template #default="{ item }">
            <div>{{ item.groupEname }} {{ item.groupCname }}</div>
          </template>
        </FIAutoInput> -->
        <FISelect
          v-if="scope.row._isNew"
          v-model="scope.row.groupEname"
          valueCustom="groupEname"
          popperClass="select-groupEname-class"
          :props="{ value: 'groupEname', label: 'groupEname' }"
          :options="userGroupList"
          :display-key="['groupEname', 'groupCname']"
          @select="handleSelect($event, scope.$index)"
          remote
          :remote-method="remoteMethod"
          clearable
          filterable
          usePagination
          :loadMoreEnd="loadMoreEnd"
          @load-more="loadMore"
        />
        <span v-if="!scope.row._isNew">{{ scope.row.groupEname }}</span>
      </template>
    </FITable>
  </FIModel>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, toRaw } from 'vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIForm from '@/components/FIForm.vue'
import FIModel from '@/components/FIModel.vue'
import { apiSaveGroupUsers, apiGetUserGroupsByUser, apiGroupMaintquery, apiGroupMaintdelete } from '@/api/user'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { apiRequestPost } from '@/api/globalApi.js'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()
const emits = defineEmits(['close', 'update:usersShow'])
const props = defineProps({
  // 圆角大小
  usersShow: {
    type: Boolean,
    default: false,
  },
  editData: {
    type: Object,
    default: () => {
      return {}
    },
  },
})
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})

const userlistCurrent = ref(1)
const loadMoreEnd = ref(false)
const register = reactive({
  userName: '',
  password: '',
  loginName: '',
  mobile: '',
  gender: '',
  email: '',
  businessPhone: '',
  jobNo: '',
  deptId: '',
})
const dataList = ref([])
const getUserList = (loginName) => {
  const par = {
    current: 1,
    size: 10,
    loginName,
    // postCname,
    // postEname,
  }
  apiGetUserGroupsByUser(par)
    .then((res) => {
      if (res.data.success) {
        dataList.value = res.data.data
        pageConfig.total = Number(res.data.data.length)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  // searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  // searchFn()
}
const tableRef = ref(null)
const handleSelect = (item, index) => {
  tableRef.value.setCellValue(index, 'groupCname', item.groupCname)
  tableRef.value.setCellValue(index, 'groupId', item.groupId)
}
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      // if (item?.groupId) ids.push(item?.groupId)
      if (item?.groupId) {
        ids.push({
          userId: props.editData.userId,
          groupId: item.groupId,
        })
      }
    })

  if (!ids.length) {
    getUserList(props.editData.loginName)
    return
  }
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('deleteGroupUsers', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        getUserList(props.editData.loginName)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const isTableLoading = ref(false)
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 页面编码
const tableId = 'pageMaint'
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
})
const columns: Column[] = reactive([
  {
    label: '用户组编码',
    prop: 'groupEname',
    align: 'center',
    // editable: false,
    editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    filterable: false,
    modelValue: { inputValue: '' },
    sortable: false,
    sortValue: '',
    required: true,
    editConfig: {
      rules: { groupEname: [{ required: true, message: '请选择用户组编码', trigger: 'change' }] },
    },
  },
  {
    label: '用户组名称',
    prop: 'groupCname',
    align: 'center',
    queryName: '',
    editable: true,
    sortable: true,
    filterable: false,
    readonly: true,
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
let visible: any = computed({
  get() {
    return props.usersShow
  },
  set(val) {
    emits('update:usersShow', val)
  },
})
const addRowSave = (data) => {
  handleSave(data, 'add')
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  // apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
  //   .then((res) => {
  //     isTableLoading.value = false
  //     if (res.data.success) {
  //       // saveSuccessful.value = true
  //       tableRef.value.clearSelection()
  //       searchFn()
  //     } else {
  //       ElMessage.error(res.data.message)
  //     }
  //   })
  //   .catch((error: any) => {
  //     isTableLoading.value = false
  //   })
}
const searchFn = (type?: string, columnsVal?: any, orgId?: any) => {
  // const obj = initSearchData(type, columnsVal, columns, state.query)
  // state.query = obj.queryData
  // columns.values = obj.columns
  // state.query.current = pageConfig.currentPage
  //   isTableLoading.value = true
  //   if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  // const par = {
  //   deptId:orgId || '',
  //   ...state.query,
  // }
  // apiUserquery(par)
  //   .then((res) => {
  //     isTableLoading.value = false
  //     if (res.data.success) {
  //       state.dataList = res.data.data.result
  //       pageConfig.pageSize = Number(res.data.data.size)
  //       pageConfig.total = Number(res.data.data.count)
  //     } else {
  //       // ElMessage.error(res.data.message)
  //     }
  //   })
  //   .catch((error: any) => {
  //     isTableLoading.value = false
  //     // 处理错误
  //     console.log('apiRequestPost---error', error)
  //   })
}

const closeClick = () => {
  visible.value = false
  emits('update:usersShow', false)
}
const saveClick = () => {
  console.log(checkedRows.value, 'checkedRows.value')
  for (let i of checkedRows.value) {
    if (!i.groupCname) {
      useMessage().warning('请选择用户组编码')
      return
    }
  }
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.groupId) {
        ids.push({
          userId: props.editData.userId,
          groupId: item.groupId,
        })
      }
    })

  const apiUrl = proxy.$Button_api('saveGroupUsers', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      if (res.data.success) {
        getUserList(props.editData.loginName)
        useMessage().success(res.data.message)
        // emits('update:usersShow', false)
      }
    })
    .catch((error: any) => {})
}
const userGroupList = ref([])
const remoteMethod = (query) => {
  console.log(query, 'query')
  userlistCurrent.value = 1
  getUserGroup(query)
}
const loadMore = () => {
  if (loadMoreEnd.value && userlistCurrent.value > 1) return
  userlistCurrent.value++
  getUserGroup('')
}
const getUserGroup = (query) => {
  const par = {
    groupAName: query || '',
    current: userlistCurrent.value,
    size: 10,
  }
  apiGroupMaintquery(par)
    .then((res) => {
      if (res.data.success) {
        // userGroupList.value = res.data.data.result
        userGroupList.value = userGroupList.value.concat(res.data.data.result)
        if (userlistCurrent.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
watch(
  () => props.editData,
  (newValue) => {
    if (newValue.loginName) {
      getUserList(newValue.loginName)
      getUserGroup()
    }
  }
)
onMounted(() => {
  //
})
</script>
<style lang="less" scoped></style>
